package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    //保存添加菜品数据
    @Override
    public void save(Category category) {
        //补全参数
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.save(category);
    }

    //分页查询管理
    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        //1.设置当前页面和页面大小
        PageHelper.startPage(page,pageSize);

        //2.查询数据
        List<Category> categoryList = categoryMapper.findAll();

        //3.把集合封装到PageInfo对象
        PageInfo<Category> pageInfo =new PageInfo<>(categoryList);

        //4.把PageInfo的数据封装到page对象中
        Page<Category> pageResult = new Page<>(pageInfo.getList(),pageInfo.getTotal(),page,pageSize);

        return pageResult;
    }

    //删除菜品
    @Override
    public void delete(Long id) {
        //删除之前查看当前类下是否有菜品
        //菜品分类
        int count1 = dishMapper.findCountByCategoryId(id);
        if(count1>0){
            //代表有菜品关联该菜系类别，抛出异常， 有没有一种异常代表了菜品已经关联类别
            throw new CustomerException("该类别已经被其他菜品关联，不能删除");
        }

        //套餐分类
        int count2 = setmealMapper.findCountByCategoryId(id);
        if (count2>0){
            throw new CustomerException("该类别已经被其他菜品关联，不能删除");
        }
        categoryMapper.delete(id);
    }

    //修改菜品信息
    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    //根据type查询菜品类型列表
    @Override
    public R<List<Category>> list(Integer type) {
        List<Category> categoryList = categoryMapper.list(type);
        return R.success(categoryList);
    }
}
